layui.define(['table', 'form', 'laytpl'], function (exports) {
    var $ = layui.$,
        table = layui.table,
        form = layui.form,
        laytpl = layui.laytpl;

    table.render({
        elem: '#userTable'
        , url: '/basicDataManager/list' //模拟接口
        , cols: [[
            {field: 'id', hide: true, title: 'ID'},
            , {field: 'basic_key', title: 'Key',minWidth: 100}
            , {field: 'basic_value', title: 'Value', minWidth: 100}
            , {field: 'date_created', title: '创建时间', minWidth: 100}
            , {field: 'edit', minWidth: 100, title: '编辑模式'}
            , {field: 'note', minWidth: 100, title: '备注'}
            , {title: '操作', width: 220, align: 'center', fixed: 'right', toolbar: '#table-useradmin-webuser'}
        ]]
        , page: true
        , limit: 30
        , height: 'full-220'
        , text: {
            none: '暂无相关数据' //默认：无数据。注：该属性为 layui 2.2.5 开始新增
        }
    });

    //监听搜索
    form.on('submit(LAY-user-front-search)', function (data) {
        var field = data.field;
        //执行重载
        table.reload('userTable', {
            where: field
        });
    });

    //监听搜索
    form.on('submit(LAY-user-front-add)', function (data) {
        var index = layer.open({
            type: 2
            , title: '添加用户'
            , content: '/user/add'
            , maxmin: true
            , area: ['800px', '500px']
            , btn: ['确定', '取消']
            , yes: function (index, layero) {
                var iframeWindow = window['layui-layer-iframe' + index]
                    , submitID = 'LAY-submit'
                    , submit = layero.find('iframe').contents().find('#' + submitID);

                //监听提交
                iframeWindow.layui.form.on('submit(' + submitID + ')', function (data) {
                    var field = data.field; //获取提交的字段
                    $.ajax({
                        url: '/user/add', method: 'post', data: field, success: (result) => {
                            table.reload('userTable'); //数据刷新
                            if (result == 1) {
                                layer.msg('添加成功！');
                            } else if (result == 0) {
                                layer.msg('添加失败，用户名重复，请重试！');
                            }else{
                                layer.msg('添加失败，请重试！');
                            }
                            layer.close(index); //关闭弹层
                        }
                    });
                });
                submit.trigger('click');
            }
        });
        layer.full(index);
    });


    //请求获取角色下拉列表
    $.ajax({
        url: "/user/getRole",
        type: 'POST',
        dataType: 'json',
        error: function () {
            layer.msg('出错啦。。。');
        },
        success: function (result) {        //动态渲染下拉列表
            for (let i = 0; i < result.length; i++) {
                $("#role_name_select").append("<option value='" + result[i].id + "'>" + result[i].permission_name + "</option>");//新增
                form.render();
            }
        }
    });


    //监听工具条
    table.on('tool(LAY-user-manage)', function (obj) {
        var data = obj.data;
        if (obj.event === 'enable') {
            let type = '启用';
            let code = 1;
            let userId = data.user_id;
            if (data.enabled == 1) {
                type = '禁用'
                code = 0;
            }
            layer.confirm(`真的要${type}该用户吗？`, function (index, layero) {
                $.ajax({
                    url: '/user/enabled', method: 'post', data: {enabled: code, userId: userId}, success: (result) => {
                        table.reload('userTable'); //数据刷新
                        if (result == 1) {
                            layer.msg('成功！');
                        } else {
                            layer.msg('失败！');
                        }
                        layer.close(index); //关闭弹层
                    }
                });
            });
        } else if (obj.event === 'edit') {
            var tr = $(obj.tr);
            var index2 = layer.open({
                type: 2
                , title: '编辑用户'
                , content: '/user/update?id=' + data.user_id
                , maxmin: true
                , area: ['800px', '600px']
                , btn: ['确定', '取消']
                , yes: function (index, layero) {
                    var iframeWindow = window['layui-layer-iframe' + index]
                        , submitID = 'LAY-submit'
                        , submit = layero.find('iframe').contents().find('#' + submitID);
                    user.setCate(layero);

                    //监听提交
                    iframeWindow.layui.form.on('submit(' + submitID + ')', function (data) {
                        var field = data.field; //获取提交的字段
                        $.ajax({
                            url: '/user/update', method: 'post', data: field, success: (result) => {

                                table.reload('userTable'); //数据刷新

                                if (result == 1) {
                                    layer.msg('成功！');
                                } else {
                                    layer.msg('失败！');
                                }
                                layer.close(index); //关闭弹层
                            }
                        });
                    });

                    submit.trigger('click');
                }
                , success: function (layero, index) {

                }
            });
            layer.full(index2);
        }
    });

    user = {
        postData: function (data, success) {
            var index;
            $.ajax({
                url: "user/add",
                type: 'POST',
                dataType: 'json',
                data,
                error: function () {
                    layer.msg('出错啦。。。');
                },
                beforeSend: function () {

                    index = layer.msg('处理中', {
                        icon: 16
                        , shade: 0.01
                        , time: 0
                    });
                },
                success: function (result) {
                    success && success();
                },
                complete: function () {
                    layer.close(index);
                }

            });
        },
        setCate: function (layero) {

            var items = layero.find('iframe').contents().find(":checkbox[lay-filter='LAY-Cate']");

            var cate = [];
            items.each(function (index, item) {
                if ($(this).is(':checked')) {
                    cate.push($(this)[0].title)
                }
            });

            layero.find('iframe').contents().find('#sp_cate').val(cate.join(","));
        }
    };

    //对外输出
    exports('user', {user});
});
